/******************************************************************************************************
Copyright (C) 2013 Mestrelab Research S.L. All rights reserved.

This file is part of the Mnova scripting toolkit.

Authorized users of Mnova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/

/*globals Application, NMRPredictor, Molecule, MessageBox, MnUi, qsTr, gc*/
/*jslint plusplus: true, indent: 4*/

function predictH1nC13() {
	"use strict";

	function getActiveMolecule(aDocWin, aMolPlugin) {
		var molec = aMolPlugin.activeMolecule();

		if (molec.isValid()) {
			return molec;
		}
		if (aDocWin.itemCount("Molecule") === 1) {
			molec = new Molecule(aDocWin.item(0, "Molecule"));
			return molec;
		}
		return undefined;
	}

	var	doc, mol, spcId1H, noSpectra, spcId13C, predictPage, width, height, spec1H, spec13C,
		toDelete = [],
		itemArray = [],
		i,
		j;

	doc = Application.mainWindow.activeDocument;
	mol = getActiveMolecule(doc, Application.molecule);

	if (!mol || !mol.isValid()) {
		MessageBox.critical(qsTr("Cannot proceed: open or paste a molecule to Mnova first."));
		return;
	}

	if (!Application.NMRPredictor) {
		MessageBox.critical(qsTr("Cannot proceed: the NMRPredict Desktop plug-in not loaded or licensed."));
	}

	noSpectra = doc.itemCount("NMR Spectrum");
	spcId1H = NMRPredictor.predict(mol, "1H");
	spcId13C = NMRPredictor.predict(mol, "13C");
	predictPage = doc.newPage(true);

	predictPage.title = "predicted 1H and 13C chemical shifts";
	width = predictPage.width;
	height = predictPage.height;

	spec1H = doc.getItem(spcId1H);
	spec1H.left = predictPage.left;
	spec1H.right = predictPage.right;
	spec1H.top = predictPage.top;
	spec1H.bottom = predictPage.top + height / 2;

	spec13C = doc.getItem(spcId13C);
	spec13C.left = predictPage.left;
	spec13C.right = predictPage.right;
	spec13C.top = predictPage.top + height / 2;
	spec13C.bottom = predictPage.bottom;

	itemArray[0] = spec1H;
	itemArray[1] = spec13C;

	predictPage.cloneItems(itemArray);
	predictPage.cloneItems(mol);

	for (i = 0; i < doc.pageCount(); i++) {
		for (j = 0; j < doc.page(i).itemCount(); j++) {
			if (doc.page(i).item(j).uuid === spcId13C || doc.page(i).item(j).uuid === spcId1H || doc.page(i).item(j).uuid === mol.uuid) {
				toDelete.push(doc.page(i).uuid);
				break;
			}
		}
	}

	gc(); // force garbage collection to free up memory
	doc.deletePages(toDelete);
	doc.update();
}

if (this.MnUi && this.MnUi.scripts_nmr) {
	MnUi.scripts_nmr.scripts_nmr_Predict1Hand13C = predictH1nC13;
}
